const bcryptjs = require("bcryptjs");
const { Sequelize, Model } = require("sequelize");
const { db } = require("../core/db");

class User extends Model {
  static async validateEmailLoin(email, secret) {
    const user = await User.findOne({
      where: {
        email,
      },
    });
    if (!user) {
      throw new global.errs.AuthFailed("email不存在");
    }

    const compare = bcryptjs.compareSync(secret, user.password);
    if (!compare) {
      throw new global.errs.AuthFailed("密码错误");
    }
    return user;
  }

  static async validateWxLoin(data){
    const user = await User.findOne({
      where:{
        openId:data.openid
      }
    })
    if(!user){
      return false
    }

    return user
  }
}

User.init(
  {
    id: {
      type: Sequelize.INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    nickname: Sequelize.STRING,
    password: {
      type: Sequelize.STRING,
      set(val) {
        const slat = bcryptjs.genSaltSync(10);
        const password = bcryptjs.hashSync(val, slat);
        this.setDataValue("password", password);
      },
    },
    email: Sequelize.STRING,
    openId: {
      type: Sequelize.STRING(64),
      unique: true,
    },
  },
  { sequelize: db, modelName: "users" }
);

module.exports = { User };
